<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>js过滤器</title>
    <script>

        window.onload=function(){
            const arr = [
                {id:1, name:"周冬雨", age: 18},
                {id:2, name:"马冬梅", age: 20},
                {id:3, name:"周杰伦", age: 33},
                {id:4, name:"温兆伦", age: 25},
            ];

            const ul = document.getElementById("ul-id");
            function search(val){
                let arrNew;
                if(val != null) {
                    arrNew = arr.filter(item => { //过滤数据
                        return item.name.indexOf(val) != -1;
                    })
                }else arrNew = arr;
            
                console.log(arrNew);

                ul.innerHTML='';
                for (const a of arrNew) {
                    var li = document.createElement("li");
                    li.innerText=JSON.stringify(a);
                    ul.appendChild(li); 
                }
            }
            search(); //初次加载

            //搜索事件
            let keyWord; //中文搜索关键词变量
            const searchId = document.getElementById("search");
            searchId.addEventListener('compositionstart', function (event) { //虚拟键盘拼写开始、在输入中文的情况下会出现虚拟拼写现象
                keyWord = event.target.value; 
                console.log("compositionstart");
            });
            searchId.addEventListener('compositionend', function (event) { //虚拟键盘拼写结束、在输入中文的情况下会出现虚拟拼写现象
                console.log("compositionend");
                if(keyWord != event.target.value) search(event.target.value); //内容发生变化则进行搜索
                keyWord = null; //清空内容标记
            });

            searchId.addEventListener('input', function (event) { //内容发生改变时触发
                if(keyWord!=null) return; //如果正在虚拟键盘拼写、则直接屏蔽
                search(event.target.value); 
            });
            
        }
    </script>
</head>
<body>
    <input id="search" type="text" autocomplete="off"> <!-- autocomplete="off" 关闭记录 -->
    <ul id="ul-id"></ul>
</body>
</html>